import 'package:chat_client/screens/mobile/menu/add_friend.dart';
import 'package:chat_client/screens/mobile/menu/create_group.dart';
import 'package:chat_client/widgets/c_popup_menu.dart';
import 'package:flutter/material.dart';

class CustomAppbar extends StatefulWidget implements PreferredSizeWidget {
  final String title;
  final Color? backgroundColor;

  const CustomAppbar({
    super.key,
    required this.title,
    this.backgroundColor,
  });

  @override
  Size get preferredSize =>
      const Size.fromHeight(kToolbarHeight); // 标准 AppBar 高度

  @override
  CustomeAppbarState createState() => CustomeAppbarState();
}

class CustomeAppbarState extends State<CustomAppbar> {
  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;

  // 显示菜单弹窗
  void _showPopup(BuildContext context) {
    final renderBox = context.findRenderObject() as RenderBox;
    final offset = renderBox.localToGlobal(Offset.zero); // 获取按钮的绝对位置

    _overlayEntry = OverlayEntry(
        builder: (context) => PopupMenu(
              onClose: () => _closePopup(),
              offset: offset,
              layerLink: _layerLink,
              menuItems: [
                MenuItem(
                  icon: Icons.person_add,
                  text: '添加好友',
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const AddFriendScreen()),
                    );
                  },
                ),
                MenuItem(
                  icon: Icons.group_add,
                  text: '发起群聊',
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const CreateGroupScreen()),
                    );
                  },
                ),
                MenuItem(
                  icon: Icons.qr_code_scanner,
                  text: '扫二维码',
                  onTap: () {
                    print('扫一扫');
                  },
                ),
              ],
            ));

    Overlay.of(context).insert(_overlayEntry!);
  }

  // 关闭弹窗
  void _closePopup() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text(widget.title),
      actions: [
        IconButton(icon: const Icon(Icons.search), onPressed: () {}),
        CompositedTransformTarget(
          link: _layerLink,
          child: IconButton(
            icon: const Icon(Icons.add_circle_outline),
            onPressed: () => _showPopup(context),
          ),
        ),
      ],
    );
  }
}
